import { message } from 'ant-design-vue'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

import { downloadTaskListApi } from '@/services/api'

/**
 * 响应数据
 *
 * SysDownloadRecordResVO
 */
export interface TaskInfo {
  /**
   * 失败数
   */
  failedNum: number
  /**
   * 总数
   */
  total: number
}

/**
 * SysDownloadRecordVO
 */
export interface FileInfo {
  id: string
  /**
   * 层级位置
   */
  location: string
  /**
   * 文件名
   */
  name: string
  /**
   * 状态 0-准备中  1-准备成功  2-准备失败
   */
  status: number
  /**
   * 状态名称
   */
  statusName: string
  /**
   * 访问地址
   */
  downloadUrl: string
  /**
   * 访问地址
   */
  url: string
}

export const useDownTaskStore = defineStore('downTaskStore', () => {
  const taskInfo = ref<TaskInfo>({
    failedNum: 0,
    total: 0
  })
  const downList = ref<FileInfo[]>()

  /**
   * 获取任务信息
   */
  const getTaskInfo = computed(() => {
    return taskInfo.value
  })

  /**
   * 获取下载列表
   */
  const getDownList = computed(() => {
    return downList.value
  })

  /**
   * 获取失败列表
   */
  const getFailedList = computed(() => {
    return downList.value?.filter(item => item.status === 2)
  })

  /**
   * 获取下载任务列表
   */
  const getSyncDownList = async () => {
    const { data } = await downloadTaskListApi.getDownList()
    const { failedNum, total, downloadRecordVoList } = data?.[0] || []
    taskInfo.value = { failedNum, total }
    downList.value = downloadRecordVoList
  }

  /**
   * 移除单个任务
   * @param fileInfo
   */
  const removeFile = async (fileInfo: FileInfo) => {
    try {
      await downloadTaskListApi.delDownRecord(fileInfo.id)({}, { isAddUid: true })
      downList.value = downList.value?.filter(item => item.id !== fileInfo.id)
      message.success('删除成功')
    } catch (error) {
      console.log(error)
    }
  }

  /**
   * 清空全部任务
   */
  const removeAllFile = async () => {
    try {
      if (!downList.value || downList.value?.length === 0) {
        return
      }
      await downloadTaskListApi.delDownRecords({}, { isAddUid: true, data: [] })
      downList.value = downList.value?.filter(item => item.status === 0)
    } catch (error) {
      console.log(error)
    }
  }

  /**
   * 清空失败任务
   */
  const removeFailedAllFile = async () => {
    try {
      const idList = downList.value?.filter(item => item.status === 2).map(item => item.id)
      if (!idList || idList?.length === 0) {
        return
      }
      await downloadTaskListApi.delDownRecords({}, { isAddUid: true, data: idList })
      downList.value = downList.value?.filter(item => item.status !== 2)
    } catch (error) {
      console.log(error)
    }
  }

  return {
    getTaskInfo,
    getDownList,
    getSyncDownList,
    getFailedList,
    downList,
    removeFile,
    removeAllFile,
    removeFailedAllFile
  }
})
